package com.xhwl.centiotdata.suppliersystem.bsedu;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import com.xhwl.common.pojo.cent.device.DeviceProductCategory;
import com.xhwl.common.pojo.cent.device.DeviceType;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.query.cent.device.DeviceTypeQuery;
import com.xhwl.common.utils.StringUtils;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.bsedu.BseduCheckDTO;
import com.xhwl.centiotdata.pojo.dto.bsedu.BseduDeviceDTO;
import com.xhwl.centiotdata.pojo.dto.bsedu.BseduVisitorDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.utils.HttpUtils;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.DateTool;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class DeviceBseduHandler {
	//每页记录条数
	private static final Integer PAGE_SIZE= 1000;
	// 数字哨兵设备类型名字
	private static final String DEVICE_TYPE_NAME = "体温检测";

	// 金茂校园查验记录为禁止进入的状态
	private static final int Forbidden = 0;

	@Autowired
	private GeneralProducer generalProducer;

	@Autowired
	private IDeviceCentService iDeviceCentService;

	public List<BseduDeviceDTO> getDevice(PedestrianIntegrationConfigDTO configDTO) throws Exception {
		Map<String, Object> body = new HashMap<>();
		body.put("orgcode", configDTO.getOrgIndexCode());
		body.put("pagesize", PAGE_SIZE);
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/json; charset=utf-8");
		headers.put("Token", getToken(configDTO));
		List<BseduDeviceDTO> dataList = new ArrayList<>();
		Integer count = 0;
		int pageNum = 1;
		do {
			body.put("pagenum", pageNum++);
			HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), "/api/third/GetDevice", null, headers,
					new HashMap<String, String>(), JSONObject.toJSONString(body));
			if (200 != response.getStatusLine().getStatusCode()) {
				throw new BusinessException("请求第三方系统异常:code=" + response.getStatusLine().getStatusCode());
			}
			HttpEntity resEntity = response.getEntity();
			String res = null;
			if (resEntity != null) {
				res = EntityUtils.toString(resEntity, "UTF-8");
				log.info("查询智慧校园防疫平台设备列表:res{}", res);
				JSONObject jsonObject = JSON.parseObject(res);
				if (jsonObject != null && "1".equals(jsonObject.getString("code"))) {
					count = jsonObject.getInteger("count");
					JSONArray dataJsonArray = jsonObject.getJSONArray("data");
					if(dataJsonArray != null && !dataJsonArray.isEmpty()) {
						for (Object objJson : dataJsonArray) {
							JSONObject jsonOb = (JSONObject)objJson;
							BseduDeviceDTO dto = new BseduDeviceDTO();
							dto.setRno(jsonOb.getInteger("rno"));
							dto.setDeviceId(jsonOb.getString("DeviceId"));
							dto.setDeviceName(jsonOb.getString("DeviceName"));
							dto.setUnitCode(jsonOb.getString("UnitCode"));
							dto.setLongitude(jsonOb.getString("Longitude"));
							dto.setLatitude(jsonOb.getString("Latitude"));
							dto.setStatus(jsonOb.getInteger("Status"));
							dataList.add(dto);
						}
					}
				}
			}
		} while (count > (pageNum - 1) * PAGE_SIZE);
		return dataList;
	}

	public List<BseduVisitorDTO> getVisitors(Integer intervalDays,PedestrianIntegrationConfigDTO configDTO) throws Exception {
		Map<String, Object> body = new HashMap<>();
		body.put("orgcode", configDTO.getOrgIndexCode());
		body.put("pagesize", PAGE_SIZE);
		if(null != intervalDays && intervalDays > 0){
			log.info("数据补救{}天",intervalDays);
			LocalDateTime lt = LocalDateTime.now().plusDays(-intervalDays.longValue());
			Date startdate = Date.from(lt.atZone( ZoneId.systemDefault()).toInstant());
			log.info("开始时间{}",startdate);
			body.put("startdate", DateTool.getFullDate().format(startdate));
		}
		else {
			body.put("startdate", DateTool.getFullDate().format(DateTool.getNextDate(new Date(), -1)));
		}
		body.put("enddate", DateTool.getFullDate().format(new Date()));
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/json; charset=utf-8");
		headers.put("Token", getToken(configDTO));
		List<BseduVisitorDTO> dataList = new ArrayList<>();
		Integer count = 0;
		int pageNum = 1;
		do {
			body.put("pagenum", pageNum++);
			HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), "/api/third/GetVisitors", null, headers,
					new HashMap<String, String>(), JSONObject.toJSONString(body));
			if (200 != response.getStatusLine().getStatusCode()) {
				throw new BusinessException("请求第三方系统异常:code=" + response.getStatusLine().getStatusCode());
			}
			HttpEntity resEntity = response.getEntity();
			String res = null;
			if (resEntity != null) {
				res = EntityUtils.toString(resEntity, "UTF-8");
				log.info("查询智慧校园防疫平台访客列表:res{}", res);
				JSONObject jsonObject = JSON.parseObject(res);
				if (jsonObject != null && "1".equals(jsonObject.getString("code"))) {
					count = jsonObject.getInteger("count");
					JSONArray dataJsonArray = jsonObject.getJSONArray("data");
					if(dataJsonArray != null && !dataJsonArray.isEmpty()) {
						for (Object objJson : dataJsonArray) {
							JSONObject jsonOb = (JSONObject)objJson;
							BseduVisitorDTO dto = new BseduVisitorDTO();
							dto.setRno(jsonOb.getInteger("rno"));
							dto.setId(jsonOb.getString("id"));
							dto.setVisitorName(jsonOb.getString("VisitorName"));
							dto.setIdno(jsonOb.getString("idno"));
							dto.setBookingDate(jsonOb.getString("BookingDate"));
							dto.setBookingTime(jsonOb.getString("BookingTime"));
							dto.setOrgCode(jsonOb.getString("OrgCode"));
							dto.setPhoto(jsonOb.getString("photo"));
							dto.setCarNo(jsonOb.getString("CarNo"));
							dto.setStatus(jsonOb.getInteger("status"));
							dataList.add(dto);
						}
					}
				}
			}
		} while (count > (pageNum - 1) * PAGE_SIZE);
		return dataList;
	}

	public List<BseduCheckDTO> getCheck(PedestrianIntegrationConfigDTO configDTO) throws Exception {
		Map<String, Object> body = new HashMap<>();
		body.put("orgcode", configDTO.getOrgIndexCode());
		body.put("pagesize", PAGE_SIZE);
		body.put("startdate", DateTool.getFullDate().format(DateTool.getNextDate(new Date(), -1)));
		body.put("enddate", DateTool.getFullDate().format(new Date()));
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/json; charset=utf-8");
		headers.put("Token", getToken(configDTO));
		List<BseduCheckDTO> dataList = new ArrayList<>();
		Integer count = 0;
		int pageNum = 1;
		do {
			body.put("pagenum", pageNum++);
			HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), "/api/third/GetCheck", null, headers,
					new HashMap<String, String>(), JSONObject.toJSONString(body));
			if (200 != response.getStatusLine().getStatusCode()) {
				throw new BusinessException("请求第三方系统异常:code=" + response.getStatusLine().getStatusCode());
			}
			HttpEntity resEntity = response.getEntity();
			String res = null;
			if (resEntity != null) {
				res = EntityUtils.toString(resEntity, "UTF-8");
				log.info("查询智慧校园防疫平台查验列表:res{}", res);
				JSONObject jsonObject = JSON.parseObject(res);
				if (jsonObject != null && "1".equals(jsonObject.getString("code"))) {
					count = jsonObject.getInteger("count");
					JSONArray dataJsonArray = jsonObject.getJSONArray("data");
					if(dataJsonArray != null && !dataJsonArray.isEmpty()) {
						for (Object objJson : dataJsonArray) {
							JSONObject jsonOb = (JSONObject)objJson;
							BseduCheckDTO dto = new BseduCheckDTO();
							dto.setRno(jsonOb.getInteger("rno"));
							dto.setId(jsonOb.getString("ID"));
							dto.setOrgCode(jsonOb.getString("orgCode"));
							dto.setIDCardNo(jsonOb.getString("IDCardNo"));
							dto.setVisitorName(jsonOb.getString("VisitorName"));
							dto.setBodyTemper(jsonOb.getString("BodyTemper"));
							dto.setVisitorType(jsonOb.getInteger("VisitorType"));
							dto.setSignInTime(jsonOb.getString("SignInTime"));
							dto.setPhoneNo(jsonOb.getString("PhoneNo"));
							dto.setUnitCode(jsonOb.getString("UnitCode"));
							dto.setUnitName(jsonOb.getString("UnitName"));
							dto.setReason(jsonOb.getString("Reason"));
							dto.setResult(jsonOb.getInteger("result"));
							dto.setSignOutTime(jsonOb.getString("SignOutTime"));
							dto.setSignDate(jsonOb.getString("signDate"));
							dataList.add(dto);
						}
					}
				}
			}
		} while (count > (pageNum - 1) * PAGE_SIZE);

		// 获取设备信息
		List<DeviceDTO> devices = this.listDevices(configDTO.getProjectId());
		log.info("获得设备信息{}", devices);
		if(!CollectionUtils.isEmpty(devices)) {
			for (BseduCheckDTO data : dataList) {
				if (Forbidden == data.getResult()) {
					AlarmManagement alarmManagement = new AlarmManagement();
					//组装公共部分数据
					alarmManagement.setProjectId(configDTO.getProjectId());
					alarmManagement.setAlarmTime(new Date());
					alarmManagement.setDeviceId(devices.get(0).getId());
					//海康门禁离线告警
					if(StringUtils.isNotEmpty(configDTO.getAlarmCode())){//私有化环境告警CODE不一致
						alarmManagement.setAlarmInventoryCode(configDTO.getAlarmCode());
					}
					else {
						alarmManagement.setAlarmInventoryCode("27592982");
					}
					generalProducer.send(AlarmConstant.JINMAO_TOPIC, alarmManagement);
				}
			}
		}
		return dataList;
	}
	/*
	 * 获取金茂校园的设备信息
	 * */
	private List<DeviceDTO> listDevices(Integer projectId){
		List<DeviceType> deviceTypeList = iDeviceCentService.getDeviceTypes(new DeviceTypeQuery()).getResult();
		AtomicInteger deviceTypeId = new AtomicInteger(1);
		for(DeviceType deviceType : deviceTypeList){
			if(deviceType.getName().contains(DEVICE_TYPE_NAME)){
				deviceTypeId.set(deviceType.getId());
				break;
			}
		};
		DevicePageQuery deviceQuery = new DevicePageQuery();
		deviceQuery.setProjectId(projectId);
		deviceQuery.setDeviceTypeIdList(Arrays.asList(deviceTypeId.get()));
		List<DeviceDTO> deviceDTOS = iDeviceCentService.listDevice(null, deviceQuery);
		if (CollectionUtils.isEmpty(deviceDTOS)) {
			log.info("没有数据啊");
			return Collections.emptyList();
		}
		return deviceDTOS;
	}

	// DeviceIntegrationConfigDTO
	private String getToken(PedestrianIntegrationConfigDTO configDTO) throws Exception {
		Map<String, String> querys = new HashMap<>();
		querys.put("appkey", configDTO.getLoginName());
		querys.put("appsecret", configDTO.getPassword());
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		HttpResponse response = HttpUtils.doPost(configDTO.getIpAndPort(), "/api/third/GetToken", null, headers,
				querys, new HashMap<String, String>());
		if (200 != response.getStatusLine().getStatusCode()) {
			throw new BusinessException("请求第三方系统异常:code=" + response.getStatusLine().getStatusCode());
		}
		HttpEntity resEntity = response.getEntity();
		String res = null;
		if (resEntity != null) {
			res = EntityUtils.toString(resEntity, "UTF-8");
			JSONObject jsonObject = JSON.parseObject(res);
			if (jsonObject != null && "1".equals(jsonObject.getString("code"))) {
				JSONObject dataJson = jsonObject.getJSONObject("data");
				if(dataJson != null) {
					return dataJson.getString("access_token");
				}
			}
		}
		throw new BusinessException("请求第三方系统获取access_token失败, res:" + res);
	}
}
